<template>
  <el-dialog
    v-model="visible"
    :title="
      isEdit ? `编辑评分模板 - ${templateData.name || ''}` : '新建评分模板'
    "
    width="1000px"
    destroy-on-close
    :before-close="handleBeforeClose"
  >
    <div v-loading="loading" class="form-container">
      <!-- 基础信息 -->
      <el-card class="form-section-card">
        <template #header>
          <span class="section-title">基础信息</span>
        </template>
        <el-form
          ref="baseFormRef"
          :model="templateData"
          label-width="120px"
          size="small"
        >
          <el-form-item
            label="模板名称 *"
            prop="name"
            :rules="[
              { required: true, message: '请输入模板名称', trigger: 'blur' },
            ]"
          >
            <el-input
              v-model="templateData.name"
              placeholder="请输入模板名称"
              maxlength="50"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="模板代码 *"
            prop="code"
            :rules="[
              { required: true, message: '请输入模板代码', trigger: 'blur' },
              {
                pattern: /^[a-zA-Z0-9_]+$/,
                message: '只能包含字母、数字和下划线',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model="templateData.code"
              placeholder="请输入模板代码（英文、数字、下划线）"
              :disabled="isEdit"
              maxlength="30"
            ></el-input>
          </el-form-item>

          <el-form-item
            v-if="!isEdit && templateMetadata?.template_types"
            label="模板类型"
            prop="template_type"
          >
            <el-select
              v-model="templateData.template_type"
              placeholder="选择模板类型（可选）"
              clearable
              @change="handleTemplateTypeChange"
              style="width: 100%"
            >
              <el-option
                v-for="type in templateMetadata.template_types"
                :key="type.type"
                :label="type.name"
                :value="type.type"
              >
                <div>
                  <span>{{ type.name }}</span>
                  <el-tag
                    v-if="type.type === 'comprehensive'"
                    size="small"
                    type="success"
                    style="margin-left: 8px"
                  >
                    推荐
                  </el-tag>
                </div>
              </el-option>
            </el-select>
            <div class="hint-text">选择模板类型可快速应用推荐配置</div>
          </el-form-item>

          <el-form-item label="版本号" prop="version">
            <el-input
              v-model="templateData.version"
              placeholder="请输入版本号"
              maxlength="10"
            ></el-input>
          </el-form-item>

          <el-form-item label="模板描述" prop="description">
            <el-input
              v-model="templateData.description"
              placeholder="请输入模板描述"
              type="textarea"
              rows="2"
              maxlength="200"
            ></el-input>
          </el-form-item>

          <el-form-item label="是否启用">
            <el-switch
              v-model="templateData.status"
              active-text="启用"
              inactive-text="禁用"
              :active-value="'启用'"
              :inactive-value="'禁用'"
            ></el-switch>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 维度配置 -->
      <el-card class="form-section-card">
        <template #header>
          <div
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
            "
          >
            <div style="display: flex; align-items: center; gap: 10px">
              <span class="section-title">维度配置（总分 100）</span>
              <el-select
                v-if="!isEdit && templateMetadata?.weight_strategies"
                v-model="selectedWeightStrategy"
                placeholder="权重分配策略"
                size="small"
                style="width: 160px"
                @change="handleWeightStrategyChange"
              >
                <el-option
                  v-for="strategy in templateMetadata.weight_strategies"
                  :key="strategy.strategy"
                  :label="strategy.name"
                  :value="strategy.strategy"
                >
                  <div>
                    <span>{{ strategy.name }}</span>
                    <el-tag
                      v-if="strategy.auto_calculate"
                      size="small"
                      type="success"
                      style="margin-left: 8px"
                    >
                      自动
                    </el-tag>
                  </div>
                </el-option>
              </el-select>
            </div>
            <el-button
              v-if="!isEdit"
              type="primary"
              size="small"
              @click="handleAddDimension"
            >
              添加维度
            </el-button>
          </div>
        </template>
        <el-table
          :data="templateData.dimensions"
          border
          size="small"
          :show-header="true"
        >
          <el-table-column label="维度名称" width="200">
            <template #default="scope">
              <el-select
                v-model="scope.row.name"
                placeholder="输入维度名称搜索"
                :loading="dimensionLoading"
                filterable
                remote
                :remote-method="
                  (query) => handleDimensionSearch(query, scope.$index)
                "
                clearable
                @focus="handleDimensionFocus(scope.$index)"
                @change="handleDimensionChange(scope.row, scope.$index)"
                style="width: 100%"
              >
                <el-option
                  v-for="dim in dimensionOptions[scope.$index] || []"
                  :key="dim.id"
                  :label="dim.dimension_name || dim.name"
                  :value="dim.dimension_name || dim.name"
                >
                  <span>{{ dim.dimension_name || dim.name }}</span>
                  <span
                    v-if="dim.dimension_code || dim.code"
                    style="color: #8492a6; font-size: 12px; margin-left: 10px"
                  >
                    ({{ dim.dimension_code || dim.code }})
                  </span>
                </el-option>
                <el-option
                  v-if="
                    (dimensionOptions[scope.$index] || []).length === 0 &&
                    !dimensionLoading &&
                    dimensionSearchQueries[scope.$index]
                  "
                  disabled
                  value=""
                >
                  未找到匹配的维度
                </el-option>
                <el-option
                  v-if="
                    (dimensionOptions[scope.$index] || []).length === 0 &&
                    !dimensionLoading &&
                    !dimensionSearchQueries[scope.$index]
                  "
                  disabled
                  value=""
                >
                  请输入维度名称搜索
                </el-option>
              </el-select>
              <div
                v-if="
                  (dimensionOptions[scope.$index] || []).length === 0 &&
                  !dimensionLoading &&
                  dimensionSearchQueries[scope.$index]
                "
                class="hint-text error-text"
                style="margin-top: 5px"
              >
                未找到匹配的维度，请尝试其他关键词
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="weight" label="权重">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <el-input
                  v-model.number="scope.row.weight"
                  type="number"
                  min="0"
                  max="100"
                  @change="calculateTotalWeight"
                  size="small"
                ></el-input>
                <span class="unit">分</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="enabled" label="启用">
            <template #default="scope">
              <el-switch
                v-model="scope.row.enabled"
                active-value="1"
                inactive-value="0"
                @change="calculateTotalWeight"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button
                type="text"
                size="small"
                @click="handleConfigRules(scope.row)"
              >
                配置规则...
              </el-button>
              <el-button
                v-if="!isEdit"
                type="text"
                size="small"
                style="color: #f56c6c"
                @click="handleRemoveDimension(scope.$index)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="total-weight">
          当前总分: {{ totalWeight }}分
          <span :class="totalWeight === 100 ? 'text-success' : 'text-danger'">
            {{ totalWeight === 100 ? "✅" : "❌" }}
          </span>
          <el-tooltip
            v-if="totalWeight !== 100"
            content="所有启用维度的权重之和必须为100分"
            placement="right"
            effect="warning"
          >
            <i class="fa fa-exclamation-circle text-warning ml-1"></i>
          </el-tooltip>
        </div>
      </el-card>

      <!-- 高级设置 -->
      <el-card class="form-section-card">
        <template #header>
          <span class="section-title">高级设置</span>
        </template>
        <el-form
          ref="advancedFormRef"
          :model="templateData.advanced_settings"
          label-width="120px"
          size="small"
        >
          <el-form-item
            label="及格分数线"
            prop="passing_score"
            :rules="[
              { required: true, message: '请输入及格分数线', trigger: 'blur' },
              {
                type: 'number',
                min: 0,
                max: 100,
                message: '请输入0-100之间的数值',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model.number="templateData.advanced_settings.passing_score"
              placeholder="请输入及格分数线"
              type="number"
              min="0"
              max="100"
            ></el-input>
            <span class="unit">分</span>
          </el-form-item>

          <el-form-item
            label="风险等级划分"
            prop="risk_levels"
            :rules="[
              {
                required: true,
                message: '请配置风险等级划分',
                trigger: 'blur',
              },
            ]"
          >
            <div
              v-if="templateMetadata?.risk_levels"
              class="risk-levels-config"
            >
              <div
                v-for="level in templateMetadata.risk_levels"
                :key="level.level"
                class="risk-level-item"
                :style="{ borderLeft: `4px solid ${level.color}` }"
              >
                <div class="risk-level-header">
                  <span class="risk-level-name">{{ level.name }}</span>
                  <el-tag
                    :color="level.color"
                    size="small"
                    style="margin-left: 8px"
                  >
                    {{ level.score_range.min }} - {{ level.score_range.max }}
                  </el-tag>
                </div>
                <div class="risk-level-description">
                  {{ level.description }}
                </div>
              </div>
            </div>
            <el-input
              v-model="templateData.advanced_settings.risk_levels"
              placeholder="例如: safe≥90, low≥80, medium≥60, high≥40, critical≥0"
              maxlength="200"
              style="margin-top: 10px"
            >
              <template #append>
                <el-button
                  v-if="templateMetadata?.risk_levels"
                  size="small"
                  @click="applyDefaultRiskLevels"
                >
                  使用默认值
                </el-button>
              </template>
            </el-input>
            <div class="hint-text">格式: 等级名称≥分数, 多个等级用逗号分隔</div>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <!-- <el-button
        type="default"
        @click="handleSave(false)"
        :disabled="totalWeight !== 100"
      >
        仅保存
      </el-button> -->
      <el-button
        type="primary"
        @click="handleSave(true)"
        :disabled="totalWeight !== 100"
      >
        保存
      </el-button>
    </template>
  </el-dialog>

  <!-- 规则配置对话框 -->
  <el-dialog
    v-model="showRuleConfigDialog"
    :title="`配置规则 - ${currentDimension.name || ''}`"
    width="600px"
    destroy-on-close
  >
    <div class="rule-config-content">
      <!-- 这里根据实际规则配置需求实现 -->
      <el-form :model="currentDimension.rules" label-width="100px" size="small">
        <el-form-item label="风险等级扣分">
          <el-table :data="currentDimension.rules" border size="small">
            <el-table-column
              prop="level"
              label="风险等级"
              width="120"
            ></el-table-column>
            <el-table-column prop="score" label="扣分数值" width="120">
              <template #default="scope">
                <el-input
                  v-model.number="scope.row.score"
                  type="number"
                  min="0"
                  max="currentDimension.weight"
                  size="small"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="规则描述">
              <template #default="scope">
                <el-input
                  v-model="scope.row.description"
                  size="small"
                ></el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="showRuleConfigDialog = false">取消</el-button>
      <el-button type="primary" @click="handleSaveRules">保存规则</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, watch, onMounted, computed } from "vue";
import { ElMessage, ElForm } from "element-plus";
import {
  getTemplateDetail,
  createTemplate,
  updateTemplate,
  getTemplateConfigMetadata,
  getDimensionList,
} from "../../../servers";

// 定义属性和事件
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  templateId: {
    type: String,
    default: "",
  },
});

const emit = defineEmits(["success", "update:modelValue"]);

// 响应式数据
const visible = ref(props.modelValue);
const loading = ref(false);
const isEdit = computed(() => !!props.templateId);
const totalWeight = ref(0);
const showRuleConfigDialog = ref(false);
const currentDimension = ref<any>({});

// 模板配置元数据
const templateMetadata = ref<any>(null);
const metadataLoading = ref(false);

// 维度搜索相关
const dimensionLoading = ref(false);
const dimensionOptions = ref<Record<number, any[]>>({});
const dimensionSearchQueries = ref<Record<number, string>>({});

// 权重策略
const selectedWeightStrategy = ref<string>("");

// 表单引用
const baseFormRef = ref<InstanceType<typeof ElForm>>();
const advancedFormRef = ref<InstanceType<typeof ElForm>>();

// 模板数据
const templateData = ref<any>({
  id: "",
  name: "",
  code: "",
  version: "1.0",
  description: "",
  status: "启用",
  template_type: "", // 模板类型
  scoring_method: "", // 评分方式
  dimensions: [
    {
      id: "vulnerability",
      name: "漏洞风险",
      weight: 25,
      enabled: "1",
      rules: [],
    },
    {
      id: "high_risk_port",
      name: "高危端口",
      weight: 15,
      enabled: "1",
      rules: [],
    },
    { id: "compliance", name: "合规状态", weight: 20, enabled: "1", rules: [] },
    {
      id: "intelligence",
      name: "威胁情报",
      weight: 20,
      enabled: "1",
      rules: [],
    },
    {
      id: "local_diff",
      name: "本地异地差异",
      weight: 15,
      enabled: "1",
      rules: [],
    },
    {
      id: "domain_weight",
      name: "域名权重",
      weight: 5,
      enabled: "1",
      rules: [],
    },
  ],
  advanced_settings: {
    passing_score: 60,
    risk_levels: "safe≥90, low≥80, medium≥60, high≥40, critical≥0",
  },
});

// 监听显示状态变化
watch(
  () => props.modelValue,
  (val) => {
    visible.value = val;
    if (val) {
      // 对话框打开时，获取模板配置元数据
      if (!templateMetadata.value) {
        fetchTemplateMetadata();
      }
    } else {
      // 重置表单
      resetForm();
      // 清理维度搜索数据
      dimensionOptions.value = {};
      dimensionSearchQueries.value = {};
    }
  }
);

// 监听模板ID变化
watch(
  () => props.templateId,
  (id) => {
    if (id && visible.value) {
      fetchTemplateDetail(id);
    } else if (!id && visible.value) {
      resetForm();
    }
  }
);

// 页面初始化
onMounted(() => {
  if (props.templateId && visible.value) {
    fetchTemplateDetail(props.templateId);
  } else {
    calculateTotalWeight();
  }
  // 获取模板配置元数据
  fetchTemplateMetadata();
});

// 获取模板配置元数据
const fetchTemplateMetadata = async () => {
  metadataLoading.value = true;
  try {
    const response = await getTemplateConfigMetadata();
    console.log("模板配置元数据响应:", response);

    // 处理响应数据（拦截器已经解析了JSON字符串）
    let metadataData = null;
    if (response?.data) {
      metadataData = response.data;
    } else if (response) {
      metadataData = response;
    }

    templateMetadata.value = metadataData;
    console.log("解析后的模板元数据:", templateMetadata.value);

    if (!templateMetadata.value) {
      console.warn("模板元数据为空");
      ElMessage.warning("获取模板配置元数据为空，将使用默认配置");
    } else {
      console.log("模板元数据获取成功:", {
        scoringMethods: templateMetadata.value.scoring_methods?.length || 0,
        weightStrategies: templateMetadata.value.weight_strategies?.length || 0,
        riskLevels: templateMetadata.value.risk_levels?.length || 0,
        templateTypes: templateMetadata.value.template_types?.length || 0,
        version: templateMetadata.value.version,
        updatedAt: templateMetadata.value.updated_at,
      });
    }
  } catch (error: any) {
    console.error("获取模板配置元数据失败:", error);
    ElMessage.error(error?.message || "获取模板配置元数据失败");
    templateMetadata.value = null;
  } finally {
    metadataLoading.value = false;
  }
};

// 维度远程搜索
const handleDimensionSearch = async (query: string, index: number) => {
  dimensionSearchQueries.value[index] = query;
  if (!query || !query.trim()) {
    dimensionOptions.value[index] = [];
    return;
  }

  dimensionLoading.value = true;
  try {
    const params: any = {
      page: 1,
      page_size: 10,
      dimension_name: query.trim(),
    };

    const response = await getDimensionList(params);
    const items = response.data?.items || response.data?.list || [];

    // 存储搜索结果
    dimensionOptions.value[index] = items.map((item: any) => ({
      id: item.id,
      dimension_code: item.dimension_code,
      dimension_name: item.dimension_name,
      max_score: item.max_score,
      weight: item.weight,
      calculation_config: item.calculation_config,
      data_source_type: item.data_source_type,
      data_source_config: item.data_source_config,
      calculation_type: item.calculation_type,
      aggregation_mode: item.aggregation_mode,
      aggregation_config: item.aggregation_config,
    }));

    console.log(`维度 ${index} 搜索结果:`, dimensionOptions.value[index]);
  } catch (error: any) {
    console.error(`维度 ${index} 搜索失败:`, error);
    ElMessage.error(error?.message || "搜索维度失败");
    dimensionOptions.value[index] = [];
  } finally {
    dimensionLoading.value = false;
  }
};

// 维度选择框获得焦点
const handleDimensionFocus = async (index: number) => {
  // 如果当前没有搜索结果，且没有搜索关键词，可以加载默认列表
  if (
    (!dimensionOptions.value[index] ||
      dimensionOptions.value[index].length === 0) &&
    !dimensionSearchQueries.value[index]
  ) {
    // 可以选择不加载默认列表，等待用户输入搜索
    // 或者加载默认列表（不传 dimension_name）
    // await handleDimensionSearch("", index);
  }
};

// 维度选择变化
const handleDimensionChange = (row: any, index: number) => {
  const selectedDimension = dimensionOptions.value[index]?.find(
    (dim) => dim.dimension_name === row.name
  );

  if (selectedDimension) {
    // 更新维度信息
    row.id = selectedDimension.dimension_code;
    row.weight = selectedDimension.max_score || selectedDimension.weight || 0;
    row.description = selectedDimension.dimension_description || "";

    // 如果有计算配置，转换为规则格式
    if (selectedDimension.calculation_config) {
      row.rules = Object.entries(selectedDimension.calculation_config).map(
        ([level, score]: [string, any]) => ({
          level,
          score: Number(score) || 0,
          description: `${level}风险项`,
        })
      );
    }

    // 保存其他配置信息
    row.data_source_type = selectedDimension.data_source_type;
    row.data_source_config = selectedDimension.data_source_config;
    row.calculation_type = selectedDimension.calculation_type;
    row.aggregation_mode = selectedDimension.aggregation_mode;
    row.aggregation_config = selectedDimension.aggregation_config;

    // 重新计算总权重
    calculateTotalWeight();
  }
};

// 添加维度
const handleAddDimension = () => {
  templateData.value.dimensions.push({
    id: "",
    name: "",
    weight: 0,
    enabled: "1",
    rules: [],
    description: "",
    data_source_type: "single_table",
    data_source_config: null,
    calculation_type: "level_mapping",
    aggregation_mode: "max",
    aggregation_config: null,
  });
  // 初始化该索引的选项和搜索查询
  const newIndex = templateData.value.dimensions.length - 1;
  dimensionOptions.value[newIndex] = [];
  dimensionSearchQueries.value[newIndex] = "";
};

// 删除维度
const handleRemoveDimension = (index: number) => {
  templateData.value.dimensions.splice(index, 1);
  // 清理对应的搜索数据
  delete dimensionOptions.value[index];
  delete dimensionSearchQueries.value[index];
  // 重新计算总权重
  calculateTotalWeight();
};

// 模板类型变化处理
const handleTemplateTypeChange = (type: string) => {
  if (!type || !templateMetadata.value?.template_types) return;

  const selectedType = templateMetadata.value.template_types.find(
    (t: any) => t.type === type
  );
  if (!selectedType) return;

  // 应用模板类型的推荐配置
  if (selectedType.default_scoring_method) {
    templateData.value.scoring_method = selectedType.default_scoring_method;
  }

  // 如果有推荐的维度，可以提示用户
  if (selectedType.recommended_dimensions) {
    ElMessage.info(
      `推荐维度: ${selectedType.recommended_dimensions.join("、")}`
    );
  }

  // 如果有推荐的权重，可以应用
  if (selectedType.suggested_weights && !isEdit.value) {
    // 清空现有维度
    templateData.value.dimensions = [];
    // 应用推荐的维度配置
    Object.entries(selectedType.suggested_weights).forEach(
      ([dimName, weight]: [string, any]) => {
        templateData.value.dimensions.push({
          id: "",
          name: dimName,
          weight: Number(weight) * 100, // 转换为分数
          enabled: "1",
          rules: [],
          description: "",
          data_source_type: "single_table",
          data_source_config: null,
          calculation_type: "level_mapping",
          aggregation_mode: "max",
          aggregation_config: null,
        });
      }
    );
    calculateTotalWeight();
  }
};

// 权重策略变化处理
const handleWeightStrategyChange = (strategy: string) => {
  if (!strategy || !templateMetadata.value?.weight_strategies) return;

  const selectedStrategy = templateMetadata.value.weight_strategies.find(
    (s: any) => s.strategy === strategy
  );
  if (!selectedStrategy) return;

  const enabledDimensions = templateData.value.dimensions.filter(
    (dim) => dim.enabled === "1"
  );
  if (enabledDimensions.length === 0) {
    ElMessage.warning("请先添加并启用至少一个维度");
    return;
  }

  if (strategy === "equal") {
    // 平均分配
    const weightPerDimension = 100 / enabledDimensions.length;
    templateData.value.dimensions.forEach((dim) => {
      if (dim.enabled === "1") {
        dim.weight = Math.round(weightPerDimension * 100) / 100;
      }
    });
    calculateTotalWeight();
    ElMessage.success("已应用平均分配策略");
  } else if (strategy === "manual") {
    // 手动分配，不做任何操作
    ElMessage.info("请手动设置各维度权重，确保总和为100");
  } else if (strategy === "importance_based") {
    // 基于重要性分配
    const importanceLevels: Record<string, number> = {
      critical: 0.5,
      high: 0.3,
      medium: 0.15,
      low: 0.05,
    };

    // 这里需要用户为每个维度设置重要性等级
    // 暂时使用简单的分配策略
    const weights = [0.4, 0.3, 0.2, 0.1];
    enabledDimensions.forEach((dim, index) => {
      dim.weight = weights[index] * 100 || 100 / enabledDimensions.length;
    });
    calculateTotalWeight();
    ElMessage.info("已应用基于重要性的分配策略（简化版）");
  }
};

// 应用默认风险等级
const applyDefaultRiskLevels = () => {
  if (!templateMetadata.value?.risk_levels) return;

  const levels = templateMetadata.value.risk_levels;
  const parts: string[] = [];

  // 按照默认顺序构建风险等级字符串
  levels.forEach((level: any) => {
    if (level.score_range?.min !== undefined) {
      parts.push(`${level.level}≥${level.score_range.min}`);
    }
  });

  templateData.value.advanced_settings.risk_levels = parts.join(", ");
  ElMessage.success("已应用默认风险等级配置");
};

// 计算总权重
const calculateTotalWeight = () => {
  let total = 0;
  templateData.value.dimensions.forEach((dim) => {
    if (dim.enabled === "1" && !isNaN(Number(dim.weight))) {
      total += Number(dim.weight);
    }
  });
  totalWeight.value = total;
};

// 格式化风险等级阈值为字符串
const formatRiskLevelThresholds = (thresholds: any) => {
  if (!thresholds || typeof thresholds !== "object") return "";

  const parts: string[] = [];
  if (thresholds.safe !== undefined) parts.push(`safe≥${thresholds.safe}`);
  if (thresholds.low !== undefined) parts.push(`low≥${thresholds.low}`);
  if (thresholds.medium !== undefined)
    parts.push(`medium≥${thresholds.medium}`);
  if (thresholds.high !== undefined) parts.push(`high≥${thresholds.high}`);
  if (thresholds.critical !== undefined)
    parts.push(`critical≥${thresholds.critical}`);

  return parts.join(", ");
};

// 映射维度数据从 API 格式到表单格式
const mapDimensionsFromApi = (dimensions: any[]) => {
  if (!dimensions || !Array.isArray(dimensions)) return [];

  return dimensions.map((dim) => ({
    id: dim.dimension_code || dim.id || "",
    name: dim.dimension_name || "",
    description: dim.dimension_description || "",
    weight: dim.max_score || dim.weight || 0,
    enabled: dim.is_enabled ? "1" : "0",
    rules: dim.calculation_config
      ? Object.entries(dim.calculation_config).map(
          ([level, score]: [string, any]) => ({
            level,
            score: Number(score) || 0,
            description: `${level}风险项`,
          })
        )
      : [],
    data_source_type: dim.data_source_type || "single_table",
    data_source_config: dim.data_source_config || null,
    calculation_type: dim.calculation_type || "level_mapping",
    aggregation_mode: dim.aggregation_mode || "max",
    aggregation_config: dim.aggregation_config || null,
  }));
};

// 获取模板详情
const fetchTemplateDetail = async (id: string) => {
  if (!id) return;

  loading.value = true;
  try {
    const { data } = await getTemplateDetail({ template_id: Number(id) });

    // 映射 API 数据到表单数据格式
    templateData.value = {
      id: data.id || id,
      name: data.template_name || "",
      code: data.template_code || "",
      version: data.version || "1.0.0",
      description: data.description || "",
      status: data.is_active ? "启用" : "禁用",
      template_type: data.template_type || "",
      scoring_method: data.scoring_method || "",
      dimensions: mapDimensionsFromApi(data.dimensions || []),
      advanced_settings: {
        passing_score: data.total_score || 100,
        risk_levels: formatRiskLevelThresholds(data.risk_level_thresholds),
      },
    };

    calculateTotalWeight();
  } catch (error: any) {
    console.error("获取模板详情失败:", error);
    ElMessage.error(error?.message || "获取模板详情失败");
  } finally {
    loading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  templateData.value = {
    id: "",
    name: "",
    code: "",
    version: "1.0",
    description: "",
    status: "启用",
    dimensions: [
      {
        id: "vulnerability",
        name: "漏洞风险",
        weight: 25,
        enabled: "1",
        rules: [],
        description: "",
        data_source_type: "single_table",
        data_source_config: null,
        calculation_type: "level_mapping",
        aggregation_mode: "max",
        aggregation_config: null,
      },
      {
        id: "high_risk_port",
        name: "高危端口",
        weight: 15,
        enabled: "1",
        rules: [],
        description: "",
        data_source_type: "single_table",
        data_source_config: null,
        calculation_type: "level_mapping",
        aggregation_mode: "max",
        aggregation_config: null,
      },
      {
        id: "compliance",
        name: "合规状态",
        weight: 20,
        enabled: "1",
        rules: [],
        description: "",
        data_source_type: "single_table",
        data_source_config: null,
        calculation_type: "level_mapping",
        aggregation_mode: "max",
        aggregation_config: null,
      },
      {
        id: "intelligence",
        name: "威胁情报",
        weight: 20,
        enabled: "1",
        rules: [],
        description: "",
        data_source_type: "single_table",
        data_source_config: null,
        calculation_type: "level_mapping",
        aggregation_mode: "max",
        aggregation_config: null,
      },
      {
        id: "local_diff",
        name: "本地异地差异",
        weight: 15,
        enabled: "1",
        rules: [],
        description: "",
        data_source_type: "single_table",
        data_source_config: null,
        calculation_type: "level_mapping",
        aggregation_mode: "max",
        aggregation_config: null,
      },
      {
        id: "domain_weight",
        name: "域名权重",
        weight: 5,
        enabled: "1",
        rules: [],
        description: "",
        data_source_type: "single_table",
        data_source_config: null,
        calculation_type: "level_mapping",
        aggregation_mode: "max",
        aggregation_config: null,
      },
    ],
    advanced_settings: {
      passing_score: 60,
      risk_levels: "safe≥90, low≥80, medium≥60, high≥40, critical≥0",
    },
  };
  calculateTotalWeight();

  if (baseFormRef.value) {
    baseFormRef.value.resetFields();
  }
  if (advancedFormRef.value) {
    advancedFormRef.value.resetFields();
  }
  // 重置权重策略
  selectedWeightStrategy.value = "";
};

// 处理规则配置
const handleConfigRules = (dimension: any) => {
  currentDimension.value = JSON.parse(JSON.stringify(dimension));
  // 初始化规则数据
  if (
    !currentDimension.value.rules ||
    currentDimension.value.rules.length === 0
  ) {
    currentDimension.value.rules = [
      { level: "critical", score: 10, description: "严重风险项" },
      { level: "high", score: 5, description: "高风险项" },
      { level: "medium", score: 3, description: "中风险项" },
      { level: "low", score: 1, description: "低风险项" },
    ];
  }
  showRuleConfigDialog.value = true;
};

// 保存规则配置
const handleSaveRules = () => {
  // 更新原维度的规则
  const index = templateData.value.dimensions.findIndex(
    (dim) => dim.id === currentDimension.value.id
  );
  if (index !== -1) {
    templateData.value.dimensions[index].rules = [
      ...currentDimension.value.rules,
    ];
  }
  showRuleConfigDialog.value = false;
  ElMessage.success("规则配置已保存");
};

// 表单验证
const validateForm = async () => {
  const baseValid = (await baseFormRef.value?.validate()) || false;
  const advancedValid = (await advancedFormRef.value?.validate()) || false;

  if (totalWeight.value !== 100) {
    ElMessage.error("所有启用维度的权重之和必须为100分");
    return false;
  }

  return baseValid && advancedValid;
};

// 解析风险等级阈值字符串
const parseRiskLevelThresholds = (riskLevelsStr: string) => {
  if (!riskLevelsStr) return undefined;

  const thresholds: Record<string, number> = {};
  const parts = riskLevelsStr.split(",").map((s) => s.trim());

  parts.forEach((part) => {
    const match = part.match(/(\w+)\s*≥\s*(\d+)/);
    if (match) {
      const level = match[1].toLowerCase();
      const score = parseInt(match[2], 10);
      if (["safe", "low", "medium", "high", "critical"].includes(level)) {
        thresholds[level] = score;
      }
    }
  });

  return Object.keys(thresholds).length > 0 ? thresholds : undefined;
};

// 映射维度数据到 API 格式
const mapDimensionsToApi = (dimensions: any[]) => {
  return dimensions
    .filter((dim) => dim.enabled === "1")
    .map((dim, index) => ({
      dimension_code: dim.id || `dim_${index}`,
      dimension_name: dim.name || "",
      dimension_description: dim.description || "",
      max_score: Number(dim.weight) || 0,
      weight: Number(dim.weight) || 0,
      data_source_type: dim.data_source_type || "single_table",
      data_source_config: dim.data_source_config || null,
      calculation_type: dim.calculation_type || "level_mapping",
      calculation_config: dim.rules
        ? dim.rules.reduce((acc: any, rule: any) => {
            acc[rule.level] = rule.score || 0;
            return acc;
          }, {})
        : null,
      aggregation_mode: dim.aggregation_mode || "max",
      aggregation_config: dim.aggregation_config || null,
      display_order: index + 1,
      is_enabled: dim.enabled === "1",
    }));
};

// 保存模板
const handleSave = async (enableAfterSave = false) => {
  if (!(await validateForm())) {
    return;
  }

  loading.value = true;
  try {
    const data = templateData.value;

    // 构建基础数据
    const baseData: any = {
      template_name: data.name || "",
      description: data.description || "",
      total_score: data.advanced_settings?.passing_score || 100,
      risk_level_thresholds: parseRiskLevelThresholds(
        data.advanced_settings?.risk_levels || ""
      ),
    };

    if (isEdit.value) {
      // 更新模板
      const updateData = {
        id: Number(props.templateId) || Number(data.id),
        ...baseData,
        is_active: enableAfterSave || data.status === "启用" ? true : false,
      };

      // 只传递有值的字段
      if (!updateData.template_name) delete updateData.template_name;
      if (!updateData.description) delete updateData.description;
      if (!updateData.risk_level_thresholds)
        delete updateData.risk_level_thresholds;

      await updateTemplate(updateData);
      ElMessage.success("模板更新成功");
    } else {
      // 创建模板
      const createData = {
        ...baseData,
        template_code: data.code || "",
        version: data.version || "1.0.0",
        is_active: enableAfterSave || data.status === "启用" ? true : false,
        is_default: false,
        created_by: "admin", // 可以从用户信息获取
        dimensions: mapDimensionsToApi(data.dimensions || []),
      };

      await createTemplate(createData);
      ElMessage.success("模板创建成功");
    }

    emit("success");
  } catch (error: any) {
    console.error("保存模板失败:", error);

    // 处理特定错误
    if (error?.code === 4000) {
      ElMessage.error(error.message || "参数验证失败，请检查输入");
    } else if (error?.code === 4001) {
      ElMessage.error(error.message || "模板代码已存在，请使用其他代码");
    } else if (error?.code === 4004) {
      ElMessage.error(error.message || "模板不存在");
    } else if (error?.code === 5000) {
      ElMessage.error(error.message || "服务器错误，请稍后重试");
    } else {
      ElMessage.error(
        error?.message ||
          (isEdit.value
            ? "模板更新失败，请稍后重试"
            : "模板创建失败，请稍后重试")
      );
    }
  } finally {
    loading.value = false;
  }
};

// 取消
const handleCancel = () => {
  emit("update:modelValue", false);
};

// 关闭前处理
const handleBeforeClose = () => {
  emit("update:modelValue", false);
  return true;
};
</script>

<style scoped lang="scss">
.form-container {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}

.form-section-card {
  margin-bottom: 16px;
  border-radius: 6px;
  border: 1px solid #f0f0f0;
}

.section-title {
  font-weight: 500;
  color: #1d2129;
}

.total-weight {
  margin-top: 12px;
  padding: 8px 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-weight: 500;
  display: flex;
  align-items: center;
}

.unit {
  margin-left: 5px;
  color: #86909c;
}

.hint-text {
  margin-top: 5px;
  font-size: 12px;
  color: #86909c;
}

.rule-config-content {
  max-height: 40vh;
  overflow-y: auto;
}

.risk-levels-config {
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.risk-level-item {
  margin-bottom: 8px;
  padding: 8px 12px;
  background-color: #fff;
  border-radius: 4px;
}

.risk-level-header {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.risk-level-name {
  font-weight: 500;
  color: #1d2129;
}

.risk-level-description {
  font-size: 12px;
  color: #86909c;
  margin-top: 4px;
}

.error-text {
  color: #f56c6c;
}
</style>
